import { useEffect, useState } from 'react';
import { Swiper, Image, Card, Tag, Button, Rate, Toast, Badge } from 'react-vant';
import './Good.css';
import { StarO, Star, createFromIconfontCN, ShoppingCartO } from '@react-vant/icons';
import chartApi from '@/apis/chartApi';
import { useNavigate, useParams } from 'react-router-dom';
import goodApi from '@/apis/goodApi';
import { getGoodsImagePath, promptResult } from '@/utils/common';
import collectionApi from '@/apis/collectionApi';
import historyApi from '@/apis/historyApi';
import orderApi from '@/apis/orderApi';
import commentApi from '@/apis/commentApi';
import MyPromotePrice from '@/components/MyPromotePrice';

const Good: React.FC = () => {
  const params = useParams();
  const IconFont = createFromIconfontCN('//at.alicdn.com/t/c/font_4934038_63ux74nr75j.js');
  const [good, setGood] = useState<ResponseGoodDetail>();
  const [comments, setCommentds] = useState<ResponseCommentsDto[]>();
  const [commentsTotal, setCommentsTotal] = useState<number>(0);
  const [allCommentsCount, setAllCommentsCount] = useState<number>(0);
  const navigate = useNavigate();

  useEffect(() => {
    const fetchGood = async () => {
      const res = await goodApi.getGoodDetail(params.id as unknown as number);
      if (res.status >= 0) {
        setGood(res.data);
        // 添加或更新历史记录
        historyApi.addHistory({ gid: params.id as unknown as number });
      }
      const res2 = await commentApi.getCommentPagination(1, 3, parseInt(params.id!));
      if (res2.status >= 0) {
        setCommentds(res2.data.data);
        setCommentsTotal(res2.data.total);
      }
      const res3 = await commentApi.getAllCommentsCount(params.id as unknown as number);
      if (res3.status >= 0) {
        setAllCommentsCount(res3.data);
      }
    };
    fetchGood();
  }, [params.id]);

  const handleAddChart = async () => {
    const res = await chartApi.addChart({ gid: params.id as unknown as number });
    if (res.status >= 0) {
      setGood((prev: any) => {
        return { ...prev, cartCount: prev.cartCount + 1 };
      });
      Toast.success('已加入购物车');
    } else {
      Toast.fail(res.message || '无响应');
    }
  };

  const buyNow = async () => {
    const res = await orderApi.submitOrder({ goodIds: [params.id], goodCounts: [1], chartIds: [] });
    if (res.status >= 0) {
      Toast.success('订单生成成功');
    } else {
      Toast.success('订单生成失败');
    }
  };

  const toChart = () => {
    navigate('/chart');
  };
  return (
    <div className="good-container">
      {/* 商品图片轮播 */}
      <div className="swiper-wrapper">
        {good && (
          <Swiper autoplay={5000}>
            {good?.detailImages.split(',').map((d: string, i: number) => {
              return (
                <Swiper.Item key={i}>
                  <Image fit="contain" height={300} src={getGoodsImagePath(good.id, d)} />
                  <div className="detailImages-tags">
                    {i + 1}/{good?.detailImages.split(',').length}
                  </div>
                </Swiper.Item>
              );
            })}
          </Swiper>
        )}
      </div>

      {/* 商品基本信息 */}
      <Card className="product-info">
        <div className="price-section">
          <MyPromotePrice price={good?.price ?? 0} propmotePrice={good?.promotePrice} />
        </div>
        <h2 className="product-title center-align-container">
          {good?.name}&nbsp;&nbsp;&nbsp;&nbsp;
          <span className="normal-font">{good?.rate.toFixed(1)}</span>
          {<Rate value={good?.rate} color="#ffd21e" voidColor="#c8c9cc" />}
        </h2>
        <div className="sales">
          已售{good?.saleCout}份{'  '} <span className="product-spec">{good?.spec}</span>
          {'  '}还剩{good?.inventory}份
        </div>
      </Card>

      {/* 用户评价 */}
      <Card className="comment-section">
        <h3>用户评价({allCommentsCount})</h3>
        {comments?.length ? (
          comments?.map((comment, index) => (
            <div
              key={index}
              className="comment-item"
              onClick={() =>
                navigate('/comment?firstId=' + comment.id + '&goodId=' + comment.goodId)
              }
            >
              <div className="comment-header">
                <span className="user">{comment.accountName}</span>
                <Rate value={comment.rate} size={12} color="#ffd21e" voidColor="#c8c9cc" />
              </div>
              <p className="comment-content">{comment.content}</p>
            </div>
          ))
        ) : (
          <div className="center-text">暂无有内容的评论</div>
        )}
        {commentsTotal > 3 ? (
          <div className="center-text padding12" onClick={() => navigate('/comment')}>
            查看更多{' >'}
          </div>
        ) : null}
      </Card>

      {/* 操作按钮 */}
      <div className="action-bar">
        <div className="icon-btn">
          <IconFont
            name="icon-shangjia"
            fontSize={28}
            onClick={() => navigate('/supplier/' + good?.sid)}
          ></IconFont>
        </div>
        <div className="icon-btn">
          {good?.isCollected ? (
            <Star
              fontSize={28} // 调整图标大小
              color="gold"
              onClick={() => {
                promptResult(
                  collectionApi.cancelCollection(good.cid as number),
                  () => {},
                  () => {
                    setGood((prev: any) => {
                      return { ...prev, isCollected: 0 };
                    });
                    Toast.success('已取消收藏');
                  }
                );
              }}
            />
          ) : (
            <StarO
              fontSize={28} // 调整图标大小
              color="#777"
              onClick={async () => {
                const res = await collectionApi.collection({ gid: params.id as unknown as number });
                if (res.status >= 0) {
                  setGood((prev: any) => {
                    return { ...prev, isCollected: 1, cid: res.data };
                  });
                  Toast.success('已收藏');
                }
              }}
            />
          )}
        </div>
        <div className="icon-btn">
          {good?.cartCount ? (
            <Badge content={good?.cartCount}>
              <ShoppingCartO fontSize={28} color="#777" onClick={toChart} />
            </Badge>
          ) : (
            <ShoppingCartO fontSize={28} color="#777" onClick={toChart} />
          )}
        </div>
        <div className="add-cart">
          <Button className="operate-round-btn-left" type="warning" onClick={handleAddChart}>
            加入购物车
          </Button>
          <Button className="operate-round-btn-right" type="danger" onClick={buyNow}>
            立即购买
          </Button>
        </div>
      </div>
    </div>
  );
};

export default Good;
